package com.ruoyi.hire.controller.company;


import com.ruoyi.common.constant.CompanyConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.hire.domain.vo.CompanyRegisterCaptchaCodeVo;
import com.ruoyi.hire.domain.vo.ValidateSmsResultVo;
import com.ruoyi.hire.service.IHireCompanyLoginService;
import com.wf.captcha.GifCaptcha;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController("CompanyCaptchaController")
public class CaptchaController {

    @Resource
    private RedisCache redisCache;


    @Resource
    private IHireCompanyLoginService hireCompanyLoginService;


    /**
     * 用人单位注册时生成验证码
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/site/hire/company/captchaImage")
    public AjaxResult getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        // 创建GifCaptcha对象
        GifCaptcha gifCaptcha = new GifCaptcha(120, 38, 4);
        // 获取验证码文本
        String verCode = gifCaptcha.text().toLowerCase();
        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CompanyConstants.COMPANY_CAPTCHA_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, verCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        ajax.put("img", gifCaptcha.toBase64());
        return AjaxResult.success(ajax);

    }


    /**
     * 用人单位注册时的验证码校验
     *
     * @param vo
     * @return
     */
    @PostMapping("/site/hire/company/check/captchaCode")
    public AjaxResult checkCode(@Validated @RequestBody CompanyRegisterCaptchaCodeVo vo) {
        Boolean result = hireCompanyLoginService.validateCaptcha(vo.getCode(), vo.getUuid());
        if (result) {
            //生成短信验证码
            String code = hireCompanyLoginService.generateTextMessageCode(6);
            //存储短信验证码
            redisCache.setCacheObject(CompanyConstants.COMPANY_REGISTER_SMS_CODE_KEY + vo.getPhoneNumber(), code, 5, TimeUnit.MINUTES);
            //发送验证码
            //TODO 注意一下，正式环境需要修改！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
            return AjaxResult.success("验证码校验成功", code);
        }
        return AjaxResult.error("验证码校验失败");
    }


}
